#!/bin/bash
:<<EOF
========================================================
	脚本说明:
	适用于alps和teksun组合结构
	用于针对代码修改的保持和还原
	适合平台项目负责人用于发布项目版本软件
========================================================
EOF
#===================================${初始化}===========================================#
#初始化变量#
RootDir=$(readlink -f .)
SCRIPT=$(basename $0)
SCRIPT=${SCRIPT%.*}
SCRIPT_VERSION="v1.2.3"
#echo ${SCRIPT}
#echo ${SCRIPT_VERSION}
#exit 1
SERVER="192.168.2.60"
USER="autoftp"
PASSWD="teksun2016"
CPUCORES=`cat /proc/cpuinfo | grep processor | wc -l`

ALPS="alps"
CUSTOM="teksun"
PUBLIC="xunhu_public"
#PUBLIC_PATH="device/teksun/${PUBLIC}"
FILELIST="file"

#=========================================${自定义函数}===================================================

function usage(){
printf "Usage:
	1.${SCRIPT} -s/-save project		保存alps下修改代码到${CUSTOM}文件夹下对应项目
	2.${SCRIPT} -p/-patch project		将${CUSTOM}下对应项目代码拷贝到alps文件夹
	3.${SCRIPT} -r/-refresh project	重新更新${CUSTOM}对应项目的私有化文件md5值
	4.${SCRIPT} -v/-verify project		检查${CUSTOM}下项目代码对应alps是否有更新
	5.${SCRIPT} -c/-clean			清空alps下的所有修改代码
	6.${SCRIPT} -l/-list			罗列teksun下的所有项目
	7.${SCRIPT} --new project eng 		全编版本,不加参数则采用out/buildinfo.txt的配置
	8.${SCRIPT} --kernel
	9.${SCRIPT} --lk 
	10.${SCRIPT} --pl
	11.${SCRIPT} --remake
版本号:${SCRIPT_VERSION}
"
exit 0
}

#格式化输出
RED="\033[0;31m"
YELLOW="\033[1;33m"
GREEN="\033[0;32m"
NO_COLOR="\033[0m"
BOLD="\033[1m"
UNDERLINE="\033[4m"
warn_debug=true
print_debug=true
print_color=36
die() {
	echo -e "==> ${RED}${@}${NO_COLOR}"
	exit 1
}

warn() {
	if [[ "$warn_debug" = true ]]; then
		echo -e "==> ${YELLOW}${@}${NO_COLOR}"
	fi
}

good() {
	echo -e "==> ${GREEN}${*}${NO_COLOR}"
}

#====================================${FTP相关函数}======================================#
#打印时间                                                            
function mPrint(){                                                
	if [ "$print_debug" == "true" ];then                              
		echo -e "\033[${print_color}m### mPrint $1\t\t\t\t${2}\t(`date +%Y_%m%d_%H:%M:%S`) ###\033[0m"
		#echo                                                         
	fi                                                               
}                                                                    

#ftp连接
function FTP(){
echo " open ${SERVER}
user ${USER} ${PASSWD}
$@
bye
" | ftp -n 
}

checkExecPath(){
	local curdir=$(readlink -f .)
	good "当前路径:$curdir"
	if [ "$(basename ${curdir})" != "${ALPS}" ];then
		die "${SCRIPT}脚本只允许在${ALPS}目录使用!"
	fi
}



forceUpdate(){
	good "当前版本:${SCRIPT_VERSION}"
	local server_backup="/scripts_tools"
	local server_size=$(FTP "ls ${server_backup}/${SCRIPT}" | awk -F" " '{print$5}')
	#good ${server_size}
	local local_size=$(ls -l `which ${SCRIPT}` | awk -F" " '{print$5}')
	#good ${local_size}
	if [ "${local_size}" != "${server_size}" ];then
		good "${SCRIPT}版本有更新"
		git-gerrit update 
		local new_version=$(${SCRIPT} -v | grep 版本号 | awk -F":" '{print$2}')
		good "最新版本:${new_version}"
		exit 0
	fi
}
#二次信息确认
secondConfirm(){
	local result=""
	local project=$1
	local action=$2
	warn "操作项目:${project}"
	warn "执行动作:${action}"
	read -p "确认执行?[Enter/Ctrl+c]:" result
	test -n "${result}" && die "中断操作"
}

#===================================${获取参数}==========================================#
commitFile(){
	#good "commitFile函数"
	local project=$1
	local backup_path="../${CUSTOM}/${project}"
	local backup_public_path="../${CUSTOM}/${PUBLIC}"
	secondConfirm $project "Save保存文件"
	#检查alps是否有提交
	checkHead ${project}
	mPrint "私有化修改代码" "开始"
	#检查私有化文件是否合理
	checkFairFile ${project}
	#删除之前保存文件
	rm -rf ${backup_path}
	#生成修改文件列表
	saveFilelist ${project}
	#根据文件列表树操作
	test -s ${backup_path}/${FILELIST} || die "未生成${backup_path}/${FILELIST}文件"
	cat ${backup_path}/${FILELIST} | while read line 
	do
		local status=$(echo ${line}| awk '{print$1}'|sed 's#[[:space:]]##g')
		local file=$(echo ${line}| awk '{print$2}')
		case ${status} in 
			M)
				#modify文件保存文件md5
				cp -rfa --parent ${file} ${backup_path}
				#git log --oneline -1 --format="%h" --name-only ${file} |xargs >> ${backup_path}/${FILELIST}.hash
				echo ${file} >> ${backup_path}/${FILELIST}.md5
				;;
			#P)
			#	#good ${PUBLIC} file
			#	cp -rfa ${file} ${backup_public_path}
			#	;;
			D)
				#D类型删除文件
				#good "delete file"
				#echo ${file} >> ${backup_path}/${FILELIST}.delete
				;;
			*)
				#新增文件直接拷贝
				cp -rfa --parent ${file} ${backup_path}
				;;
		esac
		unset file
		unset status
	done
	mPrint "私有化修改代码" "成功"
	#清除alps代码修改
	cleanFile
	#保存md5文件
	saveFileMd5 ${project}


}
patchFile(){
	#good "patchFile函数"
	local project=$1
	local backup_path="../${CUSTOM}/${project}"
	local backup_public_path="../${CUSTOM}/${PUBLIC}"
	secondConfirm $project "Patch拷贝文件"
	test -d "${backup_path}" || die "没有发现项目文件夹${backup_path}"
	#清除alps代码修改
	cleanFile
	#md5校验
	verifyMd5File ${project}
	
	mPrint "复制私有化到公共" "开始"

	test -f ${backup_path}/${FILELIST} || die "未发现${backup_path}/${FILELIST}文件"
	cat ${backup_path}/${FILELIST} | while read line 
	do
		local status=$(echo ${line}| awk '{print$1}'|sed 's#[[:space:]]##g')
		local file=$(echo ${line}| awk '{print$2}')
		case ${status} in 
			M)
				#good "修改文件:${file}"
				test -d $(dirname ${file}) || mkdir -p $(dirname ${file})
				cp -rfa ${backup_path}/${file} ./${file}
				;;
			D)
				#good "delete file"
				rm -rf $file
				;;
			#P)
			#	#good "${PUBLIC} file"
			#	cp -rfa ${backup_public_path}/$(basename ${file}) ./${PUBLIC_PATH}/
			#	;;
			*)
				#good "新增文件:${file}"
				if [ -n "${file}" ];then
					test -d $(dirname ${file}) || mkdir -p $(dirname ${file})
					cp -rfa ${backup_path}/${file} ./${file}
				fi
				;;
		esac
		unset file
		unset status
	done
	saveHistory ${project}
	mPrint "复制私有化到公共" "成功"


}
saveFilelist(){
	local project=$1
	local backup_path="../${CUSTOM}/${project}"
	test -d "${backup_path}" || mkdir -p ${backup_path}
	#撤销HEAD区的提交,避免出现多余的状态而产生bug
	git reset HEAD >/dev/null 2>/dev/null
	#根据git st的状态来保存文件
	git status -u -s --porcelain  > ${backup_path}/${FILELIST}
	#格式化filelist并且忽略xunhu_public
	sed -i 's/??/AA/g' ${backup_path}/${FILELIST}
	#过滤xunhupublic的内容
	#awk '{if($2~/device\/teksun\/xunhu_public/){$1="P";print $1" "$2}else{print$1" "$2}}' ${backup_path}/${FILELIST}
	#awk  '$2~/^/device\/teksun\/xunhu_public/{$1="P"}1' ${backup_path}/${FILELIST}
	#sed -i "/${PUBLIC}/ s/.*\ \(.*\)/P \1/" ${backup_path}/${FILELIST}
}
saveFileHash(){
	local project=$1
	local backup_path="../${CUSTOM}/${project}"
	#删除旧的hash保存文件
	rm -rf ${backup_path}/${FILELIST}.hash
	for file in  $(awk '{print$2}' ${backup_path}/${FILELIST}.md5)
	do 
		if [ $(git log --oneline -1 --format="%h" --name-only  $file |xargs |wc -w) == 1 ];then
			git log --oneline -2 --format="%h" --name-only  $file | tail -3 |xargs >> ${backup_path}/${FILELIST}.hash 
		else
		git log --oneline -1 --format="%h" --name-only  $file |xargs >> ${backup_path}/${FILELIST}.hash 
		fi
	done
}
saveFileMd5(){
	mPrint "保存修改文件的MD5" "开始"
	local project=$1
	local backup_path="../${CUSTOM}/${project}"
	#判断md5文件是否存在
	if [ -f ${backup_path}/${FILELIST}.md5 ];then  
		md5sum $(cat ${backup_path}/${FILELIST}.md5) > ${backup_path}/${FILELIST}.md5 2>/dev/null
		saveFileHash ${project}
		#git log --oneline -1 --format="%h" --name-only ${file} |xargs >> ${backup_path}/${FILELIST}.hash
	else
		warn "本次提交全是新增文件类型,无需保存md5文件"
	fi

	mPrint "保存修改文件的MD5" "成功"
}
backupFile(){
	local project=$1
	test -z "${project}" && project=$(find device/ -maxdepth 3 -name ProjectConfig.mk -exec dirname {}  \; | xargs -i basename {} | awk '{if($0~/^[a-z][0-9]/) print$1}')
	test -z "${project}" && project="project"
	mPrint "备份公共部分修改" "开始"
	mkdir -p ${RootDir}/.backup
	#定期清理非本月的备份包
	#find  ${RootDir}/.backup -not -name "*_$(date +%Y_%m)*.zip" -type f  -exec rm -rf {} ';'
	#保存之前清理非三天以内的文件
	find  ${RootDir}/.backup -not -name "*_$(date -d "-1 day" +%Y_%m%d)*.zip" -a -not -name "*_$(date -d "-2 day" +%Y_%m%d)*.zip" -a -not -name "*_$(date -d "-3 day" +%Y_%m%d)*.zip" -a -not -name "*_$(date +%Y_%m%d)*.zip" -a -type f -exec rm -rf {} ';'
	#保存备份文件
	git status -s | awk '{print$2}' |xargs zip -r ${RootDir}/.backup/${project}_$(date +%Y_%m%d_%H-%M-%S).zip > /dev/null
	mPrint "备份公共部分修改" "成功"


}

saveHistory(){
	local project=$1
	cd ../${CUSTOM}
	#保存teksun的现场
	good "保存${CUSTOM}现场:$(git log -1 --oneline ${project} | tee ../${ALPS}/.history)"
	cd - > /dev/null


}
cleanFile(){
	#清除前执行backup文件操作
	backupFile
	mPrint "清空公共部分修改" "开始"
	git reset HEAD > /dev/null
	git clean -fd  > /dev/null
	git checkout . > /dev/null
	mPrint "清空公共部分修改" "成功"

}
checkFairFile(){
	local project=$1
	mPrint "文件合理性检查" "开始"
	local errorCode="0"
	for _cf in  $(git st -s vendor/mediatek/proprietary/custom/common/cgen/cfgdefault | awk '{print$2}') 
	do 
		local _pf="vendor/mediatek/proprietary/custom/${project}/cgen/cfgdefault/$(basename $_cf)"
		test -f ${_pf} && errorCode="1"
	done
	test -d vendor/mediatek/proprietary/custom/${project}/hal/D[0-9]/ && errorCode="2"
	case $errorCode in
		1)
			die "音频参数删掉vendor/mediatek/proprietary/custom/${project}/cgen/cfgdefault/,直接修改vendor/mediatek/proprietary/custom/common/cgen/cfgdefault" 
			;;
		2)
			die "插值等hal层文件在$(file vendor/mediatek/proprietary/custom/${project}/hal/D[0-9]| awk '{print$1}')修改无效, 请在公共里修改."
			;;
	esac
	#if [ "${errorCode}" == "1" ];then
	#	die "音频参数删掉vendor/mediatek/proprietary/custom/${project}/cgen/cfgdefault/,直接修改vendor/mediatek/proprietary/custom/common/cgen/cfgdefault" ;
	#fi
	mPrint "文件合理性检查" "结束"
	unset _cf
	unset _pf
}
checkHead(){
	local project=$1
	#检查alps
	local branch=$(git branch | grep "\*" | awk '{print$2}')
	if [ $(git diff --name-only HEAD origin/${branch} | wc -l) -ne 0 ];then
		die "save文件的时候${ALPS}不允许有commit提交"
	fi
	#检查teksun
	cd ../${CUSTOM}
	#check status
	#if [ -n "$(git st -s ${project})" ];then
	#	die "save文件的时候teksun的${project}目录不能有修改,否则会被误删掉!"
	#fi
	#check log
	
	if [ "$(git log -1 --oneline ${project}| awk '{print$1}')" != "$(cat ../${ALPS}/.history| awk '{print$1}')" ];then
		warn "旧节点: $(cat ../${ALPS}/.history)"
		warn "新节点: $(git log -1 --oneline ${project})"
		die "teksun已经不是当时-p过来的现场了,请恢复到提示的teksun旧节点"
	fi
	#check orgin/log
	#if [ $(git log -1 --oneline origin/HEAD | awk '{print$1}') != $(cat ../${ALPS}/.history| awk '{print$1}') ];then
	#	warn "旧节点:$(cat ../${ALPS}/.history)"
	#	die "teksun已经不是当时-p过来的现场了,请先恢复上面提示的teksun旧节点"
	#fi
	cd - > /dev/null

}
preCommit(){
	warn $(pwd)
	local commitid=$1
	local delFileCommit="del_file_commit"
	local delFileFactory="del_file_factory"
	cd ../${CUSTOM}
	local project=$(git show -1 ${commitid} --name-only  --format="%n" | awk -F"/" '{print$1}'|uniq|grep -v "${PUBLIC}"|xargs)
	local commitMsg=$(git log -1 ${commitid} --format="%s")
	good "准备自动提交"
	if [ -n "$(git show -1 --name-only --format="%n"  | grep -E "${project}/file$")" ];then
		good "进行自动提交"
		#保存现场
		if [ -n "$(git status -s ${project})" ];then
			git status -s ${project}| awk '{print$2}' |xargs zip -r backup_${project}.zip
			git status -s ${project}| grep -Ew "^ D" > ${delFileFactory}
			git checkout ${project}
			git clean -fd ${project}
		fi
		#保存提交
		git reset --mixed ${commitid}^
		git status -s ${project}| awk '{print$2}' |xargs zip -r backup_${commitid}.zip
		git status -s ${project}| grep -Ew "^ D" > ${delFileCommit}
		git checkout ${project}
		git clean -fd ${project}
		#查找需要提前提交文件
		for file in $(git show -1 ${commitid} ${project}/file | grep "^+ M" | awk '{print$3}')
		do
			#if [ "$(git log -1 --name-status --format="%n" ${commitid}| grep ${file} | awk '{print$1}')" == "A" ];then

			if [ ! -f "${project}/$file" ];then
				local hash=$(git show -1 ${commitid} ${project}/file.hash | grep ${file}| awk '{print$1}'|tr -d "+")	
				cd ../${ALPS}
				mkdir -p ../${CUSTOM}/${project}/$(dirname ${file})
				git show ${hash}:${file} > ../${CUSTOM}/${project}/${file}
				cd - > /dev/null
			fi
		done
		#保存提前提交文件
		#git status -s ${project}| awk '{print$2}' |xargs zip -r backup_auto.zip
		#git checkout ${project}

		#unzip -o backup_auto.zip
		if [ -n "$(git status -s ${project})" ];then
			git add -A ${project}
			git commit -m "gerrit:${project}:自动提交"
		fi
		unzip -o backup_${commitid}.zip
		if [ -f "${delFileCommit}" ];then
			awk '{print$2}' ${delFileCommit} | xargs rm -rfv
		fi
		git add -A ${project}
		git commit -m "gerrit:${commitMsg}"
		#还原现场
		test -f backup_${project}.zip && unzip -o backup_${project}.zip
		if [ -f "${delFileFactory}" ];then
			 awk '{print$2}' ${delFileFactory} | xargs rm -rfv
		fi
		rm -rf "backup_${project}.zip" "backup_${commitid}.zip" "${delFileCommit}" "${delFileFactory}"
		#backup_auto.zip
	fi
	good "自动提交完成"
	cd - >/dev/null
}
verifyMd5File(){
	#good "checkFile函数"
	local project=$1
	local backup_path="../${CUSTOM}/${project}"
	mPrint "文件更新检查MD5" "开始"
	#校验md5的时候,判断md5文件是否存在
	#test -f "${backup_path}/${FILELIST}.md5" || die "没有发现${backup_path}/${FILELIST}.md5文件"
	if [ ! -s ${backup_path}/${FILELIST}.md5 ];then  
		warn "${backup_path}/${FILELIST}.md5没有发现md5文件或者文件没有内容" 
		mPrint "文件更新检查MD5" "结束"
		return 1
	else
		md5sum -c --status ${backup_path}/${FILELIST}.md5  
		local result=$?
		#good result=${result}
		if [ "${result}" != 0 ];then
			#good "${backup_path}/"
			md5sum -c --quiet ${backup_path}/${FILELIST}.md5 2>/dev/null| awk -F":" '{print$1}' >${backup_path}/${FILELIST}.conflict
			for f in $(cat ${backup_path}/${FILELIST}.conflict)
			do 
				if [ "$(echo $f | grep -wo "打开或读取失败")" ];then
					good "$f,已经被平台删除,请确认需要删除还是继续私有化."
					sed -i "/$(echo $f |awk -F'：' '{print$1}'|sed  's#/#\\/#g')/d"  ${backup_path}/${FILELIST}
					#read -p "删除吗?[y/n]" ANSWER 
					#if [ "${ANSWER}" == "y" ];then
					#	rm -rfv ${backup_path}/$(echo $f |awk -F'：' '{print$1}')
					#fi
				else
					good $f  
					git log --oneline --abbrev-commit $(grep $f ${backup_path}/${FILELIST}.hash|awk '{print$1}').. --format="%C(yellow)%h%Creset - %s %Cgreen (%ci) %C(bold blue)<%an>%Creset" $f
				fi
			done
			local APPLY=
			echo -e "私有化文件有更新:\n1. 比较文件,合入更新\n2. 忽略错误,继续执行\n3. 停止操作,还原现场" 
			read -p "默认选项[1]:" APPLY
			test -z "${APPLY}" && APPLY=1
			case  $APPLY in 
				1)good 1
					for cfile in $(cat ${backup_path}/${FILELIST}.conflict)
					do
						if [ ! "$(echo $f | grep -wo "打开或读取失败")" ];then
							bcompare ${cfile} ${backup_path}/${cfile} -leftreadonly
						fi
					done
					read -p "是否解决了冲突?"
					rm -rf ${backup_path}/${FILELIST}.conflict
					refreshMd5File ${project}
					;;
				2)good 2
					good "忽略私有化文件更新,强制刷新md5值"
					rm -rf ${backup_path}/${FILELIST}.conflict
					refreshMd5File ${project}
					;;
				3)good 3
					good "中断操作"
					rm -rf ${backup_path}/${FILELIST}.conflict
					die "中断操作"
					;;
				*)good "并没有输入什么值"
					rm -rf ${backup_path}/${FILELIST}.conflict
					;;

			esac
			unset result
			#die "私有化代码对应的公共代码有更新,请处理后再进行refreshMd5File操作"
		fi
		mPrint "文件更新检查MD5" "成功"
	fi
}

refreshMd5File(){
	mPrint "重新更新MD5文件" "开始"
	local project=$1
	local backup_path="../${CUSTOM}/${project}"
	#不存在md5文件的时候,不允许更新md5文件
	test -s ${backup_path}/${FILELIST}.md5 || die "未发现${backup_path}的md5文件"
	if [ "$(git st $(awk '{print$2}' ${backup_path}/${FILELIST}.md5) -u -s --porcelain)" ];then
		die "android:\n$(git st $(awk '{print$2}' ${backup_path}/${FILELIST}.md5) -u -s --porcelain)\n不能有改动"
	else
		md5sum $(awk '{print$2}' ${backup_path}/${FILELIST}.md5) > ${backup_path}/${FILELIST}.md5 #2>/dev/null
		local result=$?
		saveFileHash ${project}
		if [ "${result}" != 0 ];then
			good "上述私有化文件已经被平台组删除,teksun的md5和hash文件已经修改!"
		fi
	fi
	mPrint "重新更新MD5文件" "成功"
}
listProject(){
	#perl build/tools/listP.pl
	local TARGET="ProjectConfig.mk"
	local FIND_PATH="../teksun/*/device/*/"
	find $FIND_PATH -maxdepth 2 -name ${TARGET} -exec dirname {}  \; | xargs -i basename {} | awk '{if($0~/^[a-z][0-9]/) print$1}'
}
#提取对比teksun某笔提交的diff文件
diffCommit(){
	good "diff commit"
	local commitId=$1
	cd ../${CUSTOM}
	#获取文件信息
	#mkdir -p  temp/teksun
	#mkdir -p temp/alps
	#删除之前的缓存文件
	rm -rf temp/
	#获取modify文件列表
	local md5file=$(git show -1 $commitId --name-status  --format="%n" | grep "${FILELIST}.md5" | awk '{print$2}')
	local hashfile=$(git show -1 $commitId --name-status  --format="%n" | grep "${FILELIST}.hash" | awk '{print$2}')
	local project=$(echo ${md5file} | awk -F'/' '{print$1}')
	#local modifyFile=$(git show -1 ${commitId}:${md5file}|awk '{print$2}')
	local modifyFile=$(git show -1 ${commitId} --name-only --format=%n | grep -v ${FILELIST})
	#根据列表,获取当时保存的teksun的文件信息
	for file in $(echo ${modifyFile})
	do
		mkdir -p ../${ALPS}/temp/${CUSTOM}/$(dirname $file)
		git show -1 ${commitId}:${file} > ../${ALPS}/temp/${CUSTOM}/$file
	done
	#由保存的hash文件获取当时alps的文件列表
	local hashFileContent="../${ALPS}/temp/alps.file"
	git show -1 ${commitId} ${hashfile} | grep  "^+[a-z0-9]"  > ${hashFileContent}
	cd - > /dev/null
	#根据文件列表获取当时alps的文件状态
	for file in $(echo ${modifyFile})
	do
		local hash=$(cat temp/alps.file | grep ${file:${#project}+1} | awk '{print$1}')
		mkdir -p temp/alps/$(dirname $file)
		if [ -n "${hash}" ];then
			git show -1 ${hash:1}:${file:${#project}+1} > temp/alps/${file}
		fi
	done
	#调用bcompare做对比
	bcompare temp/alps temp/${CUSTOM} 
	#比较之后删除缓存文件
	rm -rf temp
}
#====================================${main}=============================================#
#将目前所有项目加入数组
add_project_combo(){
	unset ALL_PROJECTS
	local project
	for project in $(listProject); do
		if [[ ! "${ALL_PROJECTS[@]}" =~ "$project" ]] ; then
			ALL_PROJECTS=(${ALL_PROJECTS[@]} $project)
		fi
	done
}
#判断是否合法编译类型
is_current_variant(){
	local arg=$1
	local variant
	for variant in ${ALL_VARIANTS[@]}
	do
		if [ $(echo ${variant} | grep -o ${arg}) ];then
			return 0
		fi
	done
	return 1
}
#判断是否现有项目
is_current_project(){
	local arg=$1
	local project
	for project in ${ALL_PROJECTS[@]}
	do
		if [ $(echo ${project} | grep -o ${arg}) ];then
			return 0
		fi
	done
	return 1
}
#检测目前是否已经lunch了环境
check_env(){
	test -z $TARGET_PRODUCT || test -z $TARGET_BUILD_VARIANT && return 1
	return 0
}
is_current_source(){
	local project=$1
	local variant=$2
	local prefix="full"
	if [ "$(echo $TARGET_PRODUCT | grep -w ${prefix}_${project})" ]&&[ "$(echo $TARGET_BUILD_VARIANT | grep -w ${variant} )" ];then
		return 0
	fi
	return 1
}
################################################

diff_and_copy_file(){
	local src=$1
	local dest=$2
	diff $1 $2 &>/dev/null
	if [ "$?" -ne "0" ];then
		cp -rf $1 $2
	fi
}
copy_auth_file(){
	local action=$1
	local exampleProject="f825ft_35m_factory"
	local exampleSecDir="device/teksun/common/efuse/secureFile"
	local exampleUnsecDir="device/teksun/common/efuse/unsecureFile"
	local exampleList="device/teksun/common/efuse/efuse_auth_file.txt"
	#加密软件关闭fastboot模式
	if [ ${action} != "sign" ];then
		sed -i '/MTK_SEC_FASTBOOT_UNLOCK_SUPPORT[ =]*[yn]/c\MTK_SEC_FASTBOOT_UNLOCK_SUPPORT = yes' vendor/mediatek/proprietary/bootable/bootloader/lk/project/${PROJECT}.mk
	else
		sed -i '/MTK_SEC_FASTBOOT_UNLOCK_SUPPORT[ =]*[yn]/c\MTK_SEC_FASTBOOT_UNLOCK_SUPPORT = no' vendor/mediatek/proprietary/bootable/bootloader/lk/project/${PROJECT}.mk
	fi
	#循环遍历
	for _file in $(cat ${exampleList})
	do
		local src=${_file}
		local dest=$(echo ${_file}| sed -e "s/${exampleProject}/${PROJECT}/g")
		#echo src=${src}
		#echo dest=${dest}
		if [ ${action} != "sign" ];then
			diff_and_copy_file ${exampleUnsecDir}/$src $dest
		else
			diff_and_copy_file ${exampleSecDir}/$src $dest
		fi
	done
}


config_sign(){
	good "签名版本,修改参数"
	#local PROJECT=$1
	local projectConfig="vendor/mediatek/proprietary/bootable/bootloader/preloader/custom/${PROJECT}/${PROJECT}.mk"
	local secGMP="vendor/mediatek/proprietary/custom/common/secro/SECRO_GMP.ini"
	sed -i '/MTK_SEC_BOOT[ =]*ATTR/c\MTK_SEC_BOOT=ATTR_SBOOT_ENABLE' ${projectConfig}
	sed -i '/MTK_SEC_USBDL[ =]*ATTR/c\MTK_SEC_USBDL=ATTR_SUSBDL_ENABLE' ${projectConfig}
	sed -i '/MTK_SEC_MODEM_AUTH[ =]*[yn]/c\MTK_SEC_MODEM_AUTH=yes' ${projectConfig}
	sed -i '/SW_SECURE_BOOT_EN[ =]*[01]/c\SW_SECURE_BOOT_EN = 1' ${secGMP} 
	copy_auth_file sign
	#extra copy针对部分平台比较特殊需要拷贝文件预留的接口
	test -f device/teksun/common/efuse/extraCopy.sh && bash device/teksun/common/efuse/extraCopy.sh sign
	export "XUNHU_EFUSE_CONFIG=true"
}

config_unsign(){
	good "非签名版本,修改参数"
	#local PROJECT=$1
	local projectConfig="vendor/mediatek/proprietary/bootable/bootloader/preloader/custom/${PROJECT}/${PROJECT}.mk"
	local secGMP="vendor/mediatek/proprietary/custom/common/secro/SECRO_GMP.ini"
	sed -i '/MTK_SEC_BOOT[ =]*ATTR/c\MTK_SEC_BOOT=ATTR_SBOOT_ONLY_ENABLE_ON_SCHIP' ${projectConfig} 
	sed -i '/MTK_SEC_USBDL[ =]*ATTR/c\MTK_SEC_USBDL=ATTR_SUSBDL_ONLY_ENABLE_ON_SCHIP' ${projectConfig} 
	sed -i '/MTK_SEC_MODEM_AUTH[ =]*[yn]/c\MTK_SEC_MODEM_AUTH=no' ${projectConfig} 
	sed -i '/SW_SECURE_BOOT_EN[ =]*[01]/c\SW_SECURE_BOOT_EN = 0' ${secGMP}
	copy_auth_file unsign
	test -f device/teksun/common/efuse/extraCopy.sh && bash device/teksun/common/efuse/extraCopy.sh unsign
	export "XUNHU_EFUSE_CONFIG=false"
}

#获取key对应value值
getValue(){
	local file=$1
	local key=$2
	if [ -f "${file}" ];then
		local value=$(grep -v "^\s*#" ${file} | grep ${key} | tail -1 | sed 's#^[^=]*=\(.*\)$#\1#g' | sed 's#[[:space:]]##g' )
	fi
	echo ${value}
}



build_new(){
	local project=$1
	local variant=$2
	local suffix="${project}_${variant}"
	warn "rm -rf out/"
	#rm -rf out/
	ls out/| egrep -vw "buildinfo.txt" | xargs -i rm -rf out/{}
	mkdir -p out
	good "make -j${CPUCORES} 2>&1 | tee out/build_${suffix}.log"
	make -j${CPUCORES} 2>&1 | tee out/build_${suffix}.log
	if [ -f out/target/product/$project/system.img ] ;then
		#签名版本编译
		if [ "${vsign}" ];then
			good "签名版本:${vsign}"
			make -j${CPUCORES} sign-image 2>&1 | tee out/build_${suffix}_sign_image.log
			#MTK_SYSTEM_UPDATE_SUPPORT = yes
			make -j${CPUCORES} otapackage 2>&1 | tee out/build_${suffix}_otapackage.log
			good "#### ONEOS SIGN make otapackage completed successfully ####"
			return 0
			#make -j12 pl
		fi
		#ota编译
		if [ "$variant"x = "user"x ]; then
			local projectConfig=$(find out/target/product/${project}/system/ -iname ProjectConfig.mk | tail -1)
			if [ "$(getValue $projectConfig MOMAGIC_FOTA_SUPPORT)"x = "yes"x ]; then
				echo "======MOMAGIC_FOTA_SUPPORT=yes buildtype=user build otapackage start======"
				make -j${CPUCORES} otapackage 2>&1 | tee out/otapackage_${suffix}.log
			elif [ "$(getValue $projectConfig ADUPS_FOTA_SUPPORT)"x = "yes"x ]; then
				echo "======ADUPS_FOTA_SUPPORT=yes buildtype=user build otapackage start======"
				make -j${CPUCORES} otapackage 2>&1 | tee out/otapackage_${suffix}.log
			else
				echo MOMAGIC_FOTA_SUPPORT = no, ADUPS_FOTA_SUPPORT = no, no necessary to build otapackage
			fi
		fi
	else
		echo "======something error occurd during building, please check===="
	fi
}

build_kernel(){
	good "make -j${CPUCORES} kernel bootimage 2>&1 | tee out/build.log"
	make -j${CPUCORES} kernel bootimage 2>&1 | tee out/build.log
}

rebuild_all(){
	good "make -j${CPUCORES} 2>&1 | tee out/build.log"
	make -j${CPUCORES} 2>&1 | tee out/build.log
}

build_module(){
	local module=$1
	good "mmm $module 2>&1 | tee out/build.log"
	mmm $module 2>&1 | tee out/build.log
}


normal_build(){
	good "make -j${CPUCORES} $* 2>&1 | tee out/build.log"
	make -j${CPUCORES} $* 2>&1 | tee out/build.log
}


#预处理从buildinfo获取编译参数
prebuild_env(){
	local prefix="full_"
	#取默认参数
	test -f out/buildinfo.txt || die "don't found out/buildinfo.txt,please get me [project] and [variant]" 
	local project=$(cat out/buildinfo.txt|grep -w "TARGET_PRODUCT"|awk -F"=" '{print $2}')
	local variant=$(cat out/buildinfo.txt|grep -w "TARGET_BUILD_VARIANT"|awk -F"=" '{print $2}')
	#增加full前缀
	if [ $(echo $project | grep "$prefix") ];then
		project=${project:${#prefix}:${#project}}
	fi
	prepare_build $project $variant
}

#lunch项目
prepare_build(){
	source build/envsetup.sh >/dev/null 2>&1
	add_project_combo
	ALL_VARIANTS=(user userdebug eng)
	
	local project=$1
	local variant=$2
	is_current_project $project
	result_project=$?
	is_current_variant $variant
	result_variant=$?
	if [ $result_project != "0" ]||[ $result_variant != "0" ];then
		die "参数错误"
	fi
	#申明全局变量
	PROJECT=${project}
	VARIANT=${variant}
	good "lunch full_$project-$variant"
	lunch full_$project-$variant
}

#主函数入口#
function xunhu_lunch(){
	good "main函数"
	local project=$1
	local variant=$2
	local prefix="full_"
	if [ "${project}" -a "${variant}" ];then
		check_env
		if [ "$?" != "0" ];then
			warn "环境未source"
			prepare_build $project $variant

		else
			warn "环境已经lunch"
			is_current_source $project $variant
			if [ "$?" == "0" ];then
				warn "lunch参数正确"
			else
				warn "lunch参数不正确"
				prepare_build $project $variant
			fi
		fi

		#申明全局变量
		PROJECT=${PROJECT:=$project}
		VARIANT=${VARIANT:=$variant}
	else
		check_env
		if [ "$?" != "0" ];then
			warn "没有参数,并且环境没有lunch"
			prebuild_env
		else
			warn "没有给参数,环境已经lunch"
			PROJECT=${TARGET_PRODUCT:${#prefix}}
			VARIANT=${TARGET_BUILD_VARIANT}
		fi

	fi
	config_unsign
	warn "project=$PROJECT"
	warn "variant=$VARIANT"
	test  "$vsign"  && warn "sign=$vsign"

}
#

#=================================${参数选择}============================================

ARGS=$(getopt -o a:b:lspcrvd -al listp,verify,save,patch,clean,check,backup,refresh,all,diff,commit,new,remake,kernel,lk,pl,sign,version,test,help -- "$@")

eval set -- "${ARGS}" 
#echo "caicai_debug: $@"
while true  ;do
        case "$1" in
        --test) 
			vtest="yes";;
        --version|-v) 
			vVersion="yes";;
        --new|-n) 
			vnew="yes";;
        --kernel) 
			vkernel="yes";;
        --lk) 
			vlk="yes";;
        --pl) 
			vpl="yes";;
        --remake) 
			vremake="yes";;
		--listp|-l)
			vlist="yes";;
		--save|-s)
			vsave="yes";;
		--patch|-p)
			vpatch="yes";;
		--clean|-c)
			vclean="yes";;
		--backup)
			vbackup="yes";;
		--verify|-v)
			vverify="yes";;
		--refresh|-r)
			vrefresh="yes";;
		--diff|-d)
			vdiff="yes";;
		--commit)
			vcommit="yes";;
		--sign)
			vsign="yes";;
        --all) 
			vall="yes";;
        --help|-h) 
			usage;;
        --) 
			arg1="$2"; arg2="$3"; arg3="$4"; break;;
        esac
shift
done
#####################################
if [ "$vVersion" == "yes" ];then
	echo "版本号:${SCRIPT_VERSION}"
	exit 0
fi
#兼容旧版本listp
if [ "$vlist" == "yes" -o "$arg1" == "listp" ];then
	listProject 
	exit 0
fi
#检查使用路径
if [ "$vcommit" != "yes"  ];then
	checkExecPath
fi
#强制升级
forceUpdate

#######################################
if [ "$vall" == "yes" ];then
	main $arg1 $arg2
	exit 0
fi
#内调函数
if [ "$vtest" == "yes" ];then
	echo $@
	$arg1 $arg2 $arg3
	exit 0
fi
#########################################
if [ "$vnew" == "yes" ];then
	xunhu_lunch $arg1 $arg2
	build_new $PROJECT ${VARIANT}
	exit 0
fi

if [ "$vremake" == "yes" ];then
	xunhu_lunch $arg1 $arg2
	rebuild_all $PROJECT ${VARIANT}
	exit 0
fi

if [ "$vkernel" == "yes" ];then
	xunhu_lunch $arg1 $arg2
	build_kernel $PROJECT ${VARIANT}
	exit 0
fi

if [ "$vpb" == "yes" ];then
	xunhu_lunch $arg1 $arg2
	exit 0
fi

if [ "$vlk" == "yes" ];then
	xunhu_lunch $arg1 $arg2
	warn "Unknown action : lk"
	normal_build  lk
	exit 0
fi

if [ "$vsign" == "yes" ];then
	xunhu_lunch $arg1 $arg2
	config_sign
	build_new $PROJECT ${VARIANT}
	exit 0
fi

##############################################

if [ "$vsave" == "yes" -a -n "$arg1"  ];then
	commitFile $arg1
	exit 0
fi

if [ "$vpatch" == "yes" -a -n "$arg1"  ];then
	patchFile $arg1
	exit 0
fi
if [ "$vverify" == "yes" -a -n "$arg1"  ];then
	verifyMd5File $arg1
	exit 0
fi
if [ "$vclean" == "yes"  ];then
	cleanFile
	exit 0
fi
if [ "$vrefresh" == "yes" -a -n "$arg1"  ];then
	refreshMd5File $arg1
	exit 0
fi
if [ "$vcommit" == "yes" -a -n "$arg1"  ];then
	preCommit $arg1
	exit 0
fi
if [ "$vdiff" == "yes" -a -n "$arg1"  ];then
	diffCommit $arg1
	exit 0
fi
if [ "$vbackup" == "yes"  ];then
	backupFile
	exit 0
fi

#######################################
#main $1 $2 $3 $4

usage


